import logging
import os
from logging.handlers import RotatingFileHandler
from flask import request

# 创建日志目录
log_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs')
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

# 配置日志格式
formatter = logging.Formatter(
    '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
)

# 创建文件处理器
file_handler = RotatingFileHandler(
    os.path.join(log_dir, 'api.log'),
    maxBytes=10485760,  # 10MB
    backupCount=10
)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)

# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.DEBUG)

# 创建日志记录器
logger = logging.getLogger('api')
logger.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
logger.addHandler(console_handler)

def log_api_call(func):
    """API调用日志装饰器"""
    def wrapper(*args, **kwargs):
        # 记录请求信息
        logger.info(f"API Call: {request.method} {request.path}")
        logger.debug(f"Headers: {dict(request.headers)}")
        
        if request.is_json:
            logger.debug(f"Request JSON: {request.get_json()}")
        elif request.form:
            logger.debug(f"Form Data: {dict(request.form)}")
        elif request.args:
            logger.debug(f"Query Args: {dict(request.args)}")
        
        try:
            # 执行API调用
            response = func(*args, **kwargs)
            
            # 记录响应信息
            logger.info(f"API Response: {response.status_code}")
            logger.debug(f"Response Data: {response.get_json()}")
            
            return response
        except Exception as e:
            # 记录错误信息
            logger.error(f"API Error: {str(e)}", exc_info=True)
            raise
    
    wrapper.__name__ = func.__name__
    return wrapper
